import React from 'react'
import { connect } from 'dva'
import { Form ,Button,Modal,Popconfirm,Table,Row,Col,Input,Select,Cascader,Icon,Checkbox ,DatePicker,message,Spin} from 'antd'
import { Link, hashHistory } from 'dva/router'
import { cloneDeep, isEmpty } from 'lodash';
import config from 'config/config'
import { mapStateToProps } from 'utils/view_utils'
import styles from './integralExchangeNoticeStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import classnames from 'classnames/bind';
let cx=classnames.bind(styles);
import { CustomCard} from '../../../widget/Grid/CustomCard'
import FlagBtn from 'widget/FlagBtn/FlagView'
const confirm = Modal.confirm;
const FormItem = Form.Item
const InputGroup = Input.Group;
const formItemLayout = {
	labelCol: { span: 4 },
	wrapperCol: { span: 19 },
};
const formItemLayout2 = {
	labelCol: { span: 5 },
	wrapperCol: { span: 17 },
};
const formItemLayout3 = {
	labelCol: { span: 8 },
	wrapperCol: { span: 14 },
};



const integralExchangeNoticeView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let { areaList,areaList2,estateList,area1,biz,products,idArr,loading,roleList,showModal,userInfo,detail,actionType,mobileArr} = modelObj

	function inputChange(value, type, index) {
		if (type == 'areaId') {
      detail.province = value[0]
      detail.city = value[1]
			dispatch({ type: `${namespace}/getHouseArea`, payload: { province: value[0], city: value[1] } })
      
    }else if(type=='projectId'){
      console.log(value)
      detail.projectId = value.key
      detail.projectName = value.label
    }else if(type=='mobile'){
      console.log(value,index,detail.mobileArr)
      detail.mobileArr[index] = value
    }else{
			detail[type] = value
    }
    changeState({detail})
  }
  function detailSkip(type,id){
    if(type=='add'){
      console.log(detail)
      form.resetFields()
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { showModal:!showModal}
      })
    }
    if(type=='delete'){
      dispatch({
        type: `${namespace}/delete`,
        payload: { ids:id }
      })
    }
    if(type=='check'||type=='edit'){
      dispatch({
        type: `${namespace}/detail`,
        payload: { id:id }
      })
    }
    // if(type=='edit'){
    //   dispatch({
    //     type: `${namespace}/detail`,
    //     payload: { id:id }
    //   })
    // }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { actionType:type}
    })
  }
  function submit(){
    validateFields((err, values) => {
			console.log(err)
			if (!err) {
				dispatch({
					type: `${namespace}/submit`,
					payload: {}
				})
			}
		});
  }
  function updateModal(value){
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { showModal:value,detail:{} }
    })
  }
  function addMobile(){
    let detailNew = cloneDeep(detail)
    detailNew.mobileArr.push('')
    dispatch({ type: `${namespace}/updateStore`, payload: { detail:detailNew } })
  }
  function removeMobile(index){
    let detailNew = cloneDeep(detail)
    detailNew.mobileArr.splice(index, 1)
    dispatch({ type: `${namespace}/updateStore`, payload: { detail:detailNew } })
  }
 
  //修改状态
	const changeState = (payload) => {
		// console.log(payload);
		dispatch({
			type: `${namespace}/updateStore`,
			payload: { ...payload }
		})
	};

  let pageProps = {
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `3rd/integral/selectIntegrals`,
      //api_url: `admin/news/list`,
      // 接口方式
      method: "POST",
      // "data_field_name":"data",
      app: "",
      // 接口参数
      params: {
        // type:2
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      isShowLoading:loading,
      // 查询栏
      search_bar: {
        fields: [
        //   {
        //     en_name: 'regionId',
        //     zh_name: '所属区域',
        //     elem_type: 'Select',
        //     elem_valid_type: 'string',
        //     	//关联的更改的搜索字段
        //     cmpt_items:area1,
        //  },
        //   {
        //   en_name: 'province',
        //   zh_name: '所属城市',
        //   elem_type: 'Cascader',
        //   elem_valid_type: 'string',
        //   changeOnSelect:true,
        //   cmpt_items: areaList,
        //   split_keys: ['provinceCode', 'cityCode'],
        //   onFocus:()=>{
        //     area1.map((item,index)=>{
        //       // console.log(biz.queryForm.regionId,item.value)
        //       if(biz.queryForm && biz.queryForm.regionId && biz.queryForm.regionId==item.value)
        //       {
        //         // console.log(biz.queryForm.regionId,item.value)
        //         dispatch({
        //           type: `${namespace}/updateStore`,
        //           payload:{
        //             areaList:item.children,
        //           }
        //         })
        //       }
        //     })
        //   },
        // },
        // {
        //   en_name: 'projectId',
        //   zh_name: '项目名称',
        //   elem_type: 'Select',
        //   elem_valid_type: 'string',
        //   // showSearch:true,
        //   cmpt_items:products,
        //   onFocus:()=>{
        //     if(biz.queryForm && biz.queryForm.cityCode && biz.queryForm.cityCode)
        //     {
        //       dispatch({
        //         type: `${namespace}/getProduct`,
        //         payload:{
        //           cityCode:biz.queryForm.cityCode,
        //         }
        //       })
        //     }
        //   },
        // },
        {
          en_name: 'projectName',
          zh_name: '项目名称',
          elem_type: 'Input',
          elem_valid_type: 'string',
        },
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号 资讯标题 所属项目  所属城市 创建人 创建时间 更新人 更新时间   操作
      table:
        {
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 1200},
          fields: [
            {
              en_name: "projectName",
              zh_name: "项目",
            },
            {
              en_name: "tel",
              zh_name: "订单咨询热线",
            },
            {
              en_name: "mobile",
              zh_name: "兑换通知手机",
            },
            // {
            //   en_name: "createTime",
            //   zh_name: "创建时间",
            // },
            
          ],
          // 表格操作
        actions: [{
          func_name: 'edit',
          label: '操作',
          render: (item) => {
            return <FlagBtn node={<a onClick={() => detailSkip('check', item.projectId)}>查看</a>} btnId={'150103'}></FlagBtn>
          }
        },
        { 
          func_name: 'edit',
          render: (item) => {
            return <FlagBtn node={<a onClick={() => detailSkip('edit', item.projectId)}>编辑</a>} btnId={'150101'}></FlagBtn>
          }
        },
        {
          func_name: 'delete',
          render: (item) => {
            return (
              <FlagBtn
                node={<Popconfirm  Collapse title='确定要删除吗？' okText='确定' cancelText='取消' onConfirm={() => { detailSkip('delete', item.projectId) }}>
                <a>删除</a>
                </Popconfirm>}
                btnId={'150102'}>
              </FlagBtn>
            )
            
          }
        },
        ],
        },
      // 操作栏
      action_bar: [
        {
          label: '新增',
          type: 'primary',
          btnId:'150101',
          onClick: (e, row) => {
            detailSkip("add")
          }
        }
      ]
    },
  }
  
  if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/updateStore`,
				payload: { biz }
			})
		}
  }
  
  return (
    <div className={cx('pageLayout')}>
        <ListPage pageProps={pageProps} loading={loading}/>
        <Modal 
        title={actionType=='check'?'查看':'新增/编辑'}
        visible={showModal}
        okText="提交"
        onOk={()=>submit()}
        onCancel={()=>updateModal(false)}
        destroyOnClose={true}
        okButtonProps={{disabled:actionType=='check'?true:false}}
        >
          <Form>
            <Row>
								<Col className="col" span={24}>
									<FormItem {...formItemLayout} label="所属项目">
										{getFieldDecorator('projectId', {
											initialValue: detail.projectId,
											rules: [
												{
													required: true, whitespace: true, message: '请输入所属项目',
													validator: (rule, value, callback) => {
														console.log(rule, value)
													}
												},
											],
										})(
											<InputGroup compact>
                        <Cascader style={{ width: '50%' }}
												  disabled={actionType == 'check'}
													options={areaList2}
													value={[`${detail.province}`, `${detail.city}`]}
													onChange={(value, selectedOptions) => inputChange(value, "areaId")} placeholder="请选择所属城市" />
                        <Select style={{ width: '50%' }} notFoundContent={'该省市中无楼盘'}
												disabled={actionType == 'check'}
                        labelInValue
                        defaultValue={{ key:detail.projectName }}
													onChange={(e) => inputChange(e, 'projectId')} placeholder="请选择项目">
													{
														estateList && estateList.map((item, index) => (
															<Select.Option key={`house_${index}`} value={item.productId}>{item.name}</Select.Option>
														))
													}
												</Select>
											</InputGroup>
										)}
									</FormItem>
								</Col>
							</Row>
              <Row>
                <Col span={24}>
									<FormItem label='订单咨询热线'  {...formItemLayout2}>
										{getFieldDecorator('tel', {
											rules: [{
												required: true, whitespace: true, message: '订单咨询热线'
											}],
											initialValue: detail.tel ? detail.tel + '' : undefined
										})(
											<Input
												disabled={actionType == 'check'}
												placeholder='订单咨询热线' onChange={(e) => { inputChange(e.target.value, 'tel') }} />
										)}
									</FormItem>
								</Col>
              </Row>
              <Row>
                {!isEmpty(detail.mobileArr)&&detail.mobileArr.map((item,index)=>{
                  return (
                    <Row key={`mobile${index}`}> 
                      <Col span={15}>
                      <FormItem label={`兑换通知手机${index+1}`} key={'mobile' + index}  {...formItemLayout3}>
                        {getFieldDecorator(`mobile_${index}`, {
                          rules: [{
                            required: true, whitespace: true, message: '兑换通知手机'
                          }],
                          initialValue: item
                        })(
                          <Input
                            disabled={actionType == 'check'}
                            placeholder='兑换通知手机' onChange={(e) => { inputChange(e.target.value, 'mobile',index) }} />
                        )}
                      </FormItem>
                    </Col>
                    {actionType !='check'&& detail.mobileArr.length>1&&
                      <Col span={1}>
                      <Icon
                        className="dynamic-delete-button"
                        type="minus-circle-o"
                        style={{ fontSize: 16, color: "#ccc", height: 40 }}
                        onClick={() => removeMobile(index)}
                        />
                      </Col>
                    }
                    </Row>
                  )
                })
                }
                {actionType !='check'&&
                  <Col span={6}>
                    <Button onClick={(e) => { addMobile()}}>新增兑换通知手机</Button>
                  </Col>
                }
                
              </Row>
              
              
          </Form>
            
        </Modal>  
      {/* <Spin spinning={loading}>
      </Spin> */}
    </div>
  )
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(integralExchangeNoticeView))
